package com.seven.sso.service.Impl;


import com.seven.enity.Permission;
import com.seven.enity.User;
import com.seven.sso.feign.PermissionFeign;
import com.seven.sso.feign.UserFeign;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author longlong
 * @date 2024/2/21 13:44
 * description
 */
@Service
public class UserDetailService implements UserDetailsService {

    @Resource
    private UserFeign userFeign;
    @Resource
    private PermissionFeign permissionFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userFeign.getByName(username);

        //2.封装用户信息
        if (user!=null){
            //1.2查询用户权限信息
            List<Permission> allPermission = permissionFeign.getByUserId(user.getId());
            List<GrantedAuthority> authorities = new ArrayList<>();
            for(Permission per:allPermission) {
                if (per.getPermissionValue() != null) {
                    SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(per.getPermissionValue());
                    authorities.add(simpleGrantedAuthority);
                }
            }
            org.springframework.security.core.userdetails.User user1 = new
                    org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
            return user1;
        }
        //2.3返回null，由框架提供默认的UserDetailsService实现类进行处理
        return null;
    }
}
